import 'dart:collection';
import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:opene/app_constant.dart';
import 'package:opene/app_theme.dart';
import 'package:opene/app_utils.dart';
import 'package:opene/base/base_state.dart';
import 'package:opene/base/loading.dart';
import 'package:opene/net/method/base_method.dart';
import 'package:opene/net/network_manager.dart';
import 'package:opene/net/response/base_response.dart';
import 'package:opene/ui/b2cpick/b2cpickmodel.dart';
import 'package:opene/ui/b2cpick/b2cpickoblpnscreen.dart';
import 'package:opene/ui/tally/tallymodel.dart';
import 'package:opene/ui/tally/tallyskuscreen.dart';
import 'package:toast/toast.dart';

class B2CPickScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return B2CPickScreenPage();
  }
}

class B2CPickScreenPage extends StatefulWidget {
  @override
  _B2CPickScreenPageState createState() => _B2CPickScreenPageState();
}

class _B2CPickScreenPageState extends BaseState<B2CPickScreenPage> {
  final TextEditingController dateController = TextEditingController();
  final controller = ScrollController();

  int index = 0, position;
  List<B2CPickBean> data = new List();

  @override
  String setTitle({String title}) {
    return !Utils.isEmpty(title) ? title : "Pickup:Pending Jobs";
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    Future.delayed(Duration(milliseconds: 300), () {
      setState(() {
        getTallyContainerNo();
      });
    });
  }

  @override
  Widget getViewBinding() {
    return Container(
      margin: EdgeInsets.only(left: 15, right: 10, top: 10),
      child: setListView(),
    );
  }

  ListView setListView() {
    return ListView.builder(
      shrinkWrap: true,
      // physics: NeverScrollableScrollPhysics(),
      itemCount: data == null ? 0 : data.length,
      itemBuilder: (context, one) {
        B2CPickBean b2cPickBean = data[one];
        if (b2cPickBean.isDown == null) {
          b2cPickBean.isDown = false;
        }
        return Column(
          children: [
            Row(
              children: [
                GestureDetector(
                  onTap: () {
                    setState(() {
                      setState(() {
                        index = one;
                        setChoose(one, -1);
                      });
                    });
                  },
                  child: Icon(
                    b2cPickBean.chooseNum == 1
                        ? Icons.radio_button_on
                        : b2cPickBean.chooseNum == 2
                            ? Icons.add_task
                            : Icons.radio_button_off,
                    size: 20,
                    color: b2cPickBean.chooseNum == 1 || b2cPickBean.chooseNum == 2 ? MyAppTheme.nearlyBlue : MyAppTheme.grey,
                  ),
                ),
                Expanded(
                    flex: 1,
                    child: Text(
                      "${b2cPickBean.pickNo} (${b2cPickBean.completeQty}/${b2cPickBean.totalQty})",
                      style: MyAppTheme.text,
                    )),
                GestureDetector(
                  onTap: () {
                    setState(() {
                      b2cPickBean.isDown = !b2cPickBean.isDown;
                    });
                  },
                  child: Icon(
                    b2cPickBean.isDown ? Icons.keyboard_arrow_up : Icons.keyboard_arrow_down,
                    size: 20,
                    color: MyAppTheme.nearlyBlue,
                  ),
                ),
              ],
            ),
            Visibility(visible: b2cPickBean.isDown ? true : false, child: setListItemView(one, b2cPickBean.childPicks)),
            // Expanded(
            //   child: Visibility(visible: tally.click, child: setListViewItem(tally.list)),
            // ),
            Divider(),
          ],
        );
      },
    );
  }

  ListView setListItemView(int one, List<ChildPick> childPicks) {
    return ListView.builder(
      shrinkWrap: true,
      // physics: NeverScrollableScrollPhysics(),
      itemCount: childPicks == null ? 0 : childPicks.length,
      itemBuilder: (context, two) {
        ChildPick childPick = childPicks[two];
        if (childPick.isChoose == null) {
          childPick.isChoose = false;
        }
        return Row(
          children: [
            SizedBox(
              width: 10,
            ),
            Visibility(
              visible: Utils.isEmpty(childPick.pickNo) || (childPick.pickNo == "NONE Location") ? false : true,
              child: GestureDetector(
                onTap: () {
                  if (Utils.getStringisEmpty(childPick.pickNo) == "NONE Location") {
                    B2CPickBean b2cPickBean = data[one];

                    B2CPickBean pickupPol3Qr = new B2CPickBean();
                    pickupPol3Qr.id = childPick.id;
                    pickupPol3Qr.pickNo = childPick.pickNo;
                    pickupPol3Qr.totalQty = childPick.totalQty;
                    pickupPol3Qr.completeQty = childPick.completeQty;
                    List<ChildPick> locations = new List();
                    locations.add(childPick);
                    pickupPol3Qr.isNoneLocation = true;
                    pickupPol3Qr.childPicks = locations;
                    Navigator.push(
                      context,
                      MaterialPageRoute(builder: (context) => B2CPickOBLPNScreen(b2cPickBean: pickupPol3Qr)),
                    ).then((value) => {getTallyContainerNo()});
                    return;
                  }
                  setState(() {
                    index = one;
                    setChoose(one, two);
                  });
                },
                child: Icon(
                  childPick.isChoose ? Icons.radio_button_on : Icons.radio_button_off,
                  size: 20,
                  color: childPick.isChoose ? MyAppTheme.nearlyBlue : MyAppTheme.grey,
                ),
              ),
            ),
            Visibility(
              visible: Utils.isEmpty(childPick.pickNo) || (childPick.pickNo == "NONE Location") ? true : false,
              child: SizedBox(
                width: 20,
              ),
            ),
            Expanded(
                flex: 1,
                child: GestureDetector(
                  onTap: () {
                    if (Utils.getStringisEmpty(childPick.pickNo) == "NONE Location") {
                      B2CPickBean b2cPickBean = data[one];

                      B2CPickBean pickupPol3Qr = new B2CPickBean();
                      pickupPol3Qr.id = childPick.id;
                      pickupPol3Qr.pickNo = childPick.pickNo;
                      pickupPol3Qr.totalQty = childPick.totalQty;
                      pickupPol3Qr.completeQty = childPick.completeQty;
                      List<ChildPick> locations = new List();
                      locations.add(childPick);
                      pickupPol3Qr.isNoneLocation = true;
                      pickupPol3Qr.childPicks = locations;
                      Navigator.push(
                        context,
                        MaterialPageRoute(builder: (context) => B2CPickOBLPNScreen(b2cPickBean: pickupPol3Qr)),
                      ).then((value) => {getTallyContainerNo()});
                      return;
                    }
                    setState(() {
                      index = one;
                      setChoose(one, two);
                    });
                  },
                  child: Text(
                    "${childPick.pickNo} (${childPick.completeQty}/${childPick.totalQty})",
                    style: MyAppTheme.text13,
                  ),
                )
            ),
          ],
        );
      },
    );
  }

  int setChoose(int one, int two) {
    for (int i = 0; i < data.length; i++) {
      //遍历,非点击项其他改为非选择
      if (i == one) {
        continue;
      }
      B2CPickBean pickupPol3 = data[i];
      int chooseNum = pickupPol3.chooseNum;
      if (chooseNum == null) {
        chooseNum = 0;
      }
      if (one == -1 && two == -1) {
        //reset
        if (chooseNum > 0) {
          //有选择
          if (pickupPol3.childPicks == null) {
            continue;
          }
          for (ChildPick locations in pickupPol3.childPicks) {
            locations.isChoose = false;
          }
        }

        pickupPol3.chooseNum = 0;
      } else if (chooseNum > 0 && i != one) {
        //已有选择
        return -1;
      }
      pickupPol3.isDown = false;
    }
    if (one == -1 && two == -1) {
      //reset
      return 0;
    }
    if (two == -1) {
      //父级别列表操作
      B2CPickBean pickupPol3 = data[one];
      switch (Utils.getIntegerisEmpty(pickupPol3.chooseNum)) {
        case 0:
        case 1:
          pickupPol3.chooseNum = 2;
          pickupPol3.isDown = true;
          if (pickupPol3.childPicks == null) {
            break;
          }
          for (ChildPick locations in pickupPol3.childPicks) {
            if (Utils.getStringisEmpty(locations.pickNo) == "NONE Location") {
              locations.isChoose = false;
            } else {
              locations.isChoose = true;
            }
          }
          break;
        case 2:
          pickupPol3.chooseNum = 0;
          if (pickupPol3.childPicks == null) {
            break;
          }
          for (ChildPick locations in pickupPol3.childPicks) {
            locations.isChoose = false;
          }
          break;
      }
      return 0;
    }

    //紫级别列表操作
    int totalNum = 0;
    B2CPickBean pickupPol3 = data[one];
    ChildPick locations = pickupPol3.childPicks[two];
    locations.isChoose = (!locations.isChoose);

    for (int i = 0; i < pickupPol3.childPicks.length; i++) {
      if (pickupPol3.childPicks[i].isChoose) {
        totalNum++;
      }
    }

    if (totalNum == pickupPol3.childPicks.length) {
      //子列表全选
      pickupPol3.chooseNum = 2;
      return 0;
    }
    if (totalNum > 0) {
      //部分选择
      pickupPol3.chooseNum = 1;
      return 0;
    }
    pickupPol3.chooseNum = 0;
  }

  @override
  void setNext() {
    ToastContext().init(context);
    if (index == -1) {
      Toast.show("Please select Pending Jobs", duration: Toast.lengthShort, gravity: Toast.bottom);
      return;
    }
    B2CPickBean pickupPol3 = data[index];

    if (Utils.getIntegerisEmpty(pickupPol3.chooseNum) == 0) {
      Toast.show("Please select Pending Jobs", duration: Toast.lengthShort, gravity: Toast.bottom);
      return;
    }

    B2CPickBean b2cPickBean = new B2CPickBean();
    b2cPickBean.id = pickupPol3.id;
    b2cPickBean.pickNo = pickupPol3.pickNo;
    b2cPickBean.totalQty = pickupPol3.totalQty;
    b2cPickBean.completeQty = pickupPol3.completeQty;
    List<ChildPick> locations = new List();
    print("object:${pickupPol3.childPicks.length}");
    for (ChildPick locationsTemp in pickupPol3.childPicks) {
      if (locationsTemp.isChoose) {
        locations.add(locationsTemp);
      }
    }
    b2cPickBean.childPicks = locations;
    print("childPicks:${b2cPickBean.childPicks.length}");
    Navigator.push(
      context,
      MaterialPageRoute(builder: (context) => B2CPickOBLPNScreen(b2cPickBean: b2cPickBean)),
    ).then((value) => {getTallyContainerNo()});
  }

  @override
  void setReset() {
    setState(() {
      textEditingController.text = "";
      index = -1;
      setChoose(-1, -1);
    });
  }

  void getTallyContainerNo() async {
    try {
      // 显示加载中对话框
      LoadingIndicator.show(context);
    } catch (e) {
      e.toString();
    }
    PickupPol3CategoryQr pickupPol3CategoryQr = new PickupPol3CategoryQr();
    var json = jsonEncode(pickupPol3CategoryQr);

    BaseResponse baseResponse = await NetworkManager().request(context, Constants.pick_b2c_v2_queryPendingPicks, method: BaseMethod.post, data: json);

    try {
      // 在需要的时候隐藏加载中对话框
      LoadingIndicator.hide();
    } catch (e) {
      e.toString();
    }

    if (baseResponse.status == 200) {
      setState(() {
        data = baseResponse.data == null ? null : (new List<dynamic>.from(baseResponse.data).map((userJson) => B2CPickBean.fromJson(userJson)).toList());
      });
    } else {
      ToastContext().init(context);
      Toast.show(Utils.getStringisEmpty(baseResponse.msg), duration: Toast.lengthShort, gravity: Toast.bottom);
    }
  }

  @override
  void showFileUploadData(String path, int type, int position, bool isSubmit) {
    // TODO: implement showFileUploadData
  }
}
